package com.example.papercut.service.impl;

import com.example.papercut.entity.PapercutTemplate;
import com.example.papercut.entity.User;
import com.example.papercut.entity.TextureTemplate;
import com.example.papercut.entity.UserCreation;
import com.example.papercut.mapper.UserCreationMapper;
import com.example.papercut.service.UserCreationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserCreationServiceImpl implements UserCreationService {

    private final UserCreationMapper creationMapper;

    @Autowired
    public UserCreationServiceImpl(UserCreationMapper creationMapper) {
        this.creationMapper = creationMapper;
    }

    @Override
@Transactional
public void saveCreation(UserCreation creation) {
        
        // 🚨 检查基本 ID 字段是否接收成功
        if (creation.getUserId() == null || creation.getTemplateId() == null || creation.getTextureId() == null) {
            throw new IllegalArgumentException("创作记录必须包含用户ID、模板ID和纹理ID。");
        }
        
        // 【✅ 核心修复：手动创建关联对象的占位符并设置 ID】
        // 这样即使不加载完整的 User/Template 对象，Mapper 也可以通过 .getUser().getId() 获取到正确的 ID。
        
        // 修复 user 字段
        User userPlaceholder = new User(); // 假设User有构造函数或Lombok
        userPlaceholder.setId(creation.getUserId());
        creation.setUser(userPlaceholder);

        // 修复 basePapercut 字段
        PapercutTemplate templatePlaceholder = new PapercutTemplate();
        templatePlaceholder.setId(creation.getTemplateId());
        creation.setBasePapercut(templatePlaceholder);
        
        // 修复 selectedTexture 字段
        TextureTemplate texturePlaceholder = new TextureTemplate();
        texturePlaceholder.setId(creation.getTextureId());
        creation.setSelectedTexture(texturePlaceholder);
        
        // 修复 creationTime 字段 (如果Mapper没有用NOW())
        if (creation.getCreationTime() == null) {
            creation.setCreationTime(LocalDateTime.now());
        }
        
        creationMapper.insertUserCreation(creation);
    }
    @Override
    public List<UserCreation> getCreationsByUserId(Integer userId) {
        return creationMapper.findCreationsByUserId(userId);
    }

    @Override
    public UserCreation getCreationDetails(Integer id) {
        return creationMapper.findCreationById(id);
    }
}